﻿(function ($) {
    var itemlookup = { $table: null, suffix: "", $target: null, pk: "id" };
    $.extend({
        jtoCreateMutil: function ($input) {
            var valstr = $input.val();
            if (valstr) {
                var valarry = valstr.split(',');
                var inputname = $input.attr("name");
                var boxname = inputname.replace(".", "_") + "spanToMutilCols";
                var $box = $("<span id='" + boxname + "'></span>");
                $("#" + boxname).remove();
                for (var i = 0; i < valarry.length; i++) {
                    var name = inputname.replace(".", "[" + i + "].");
                    var $target = $("<input type='hidden' id='" + name + "' name='" + name + "' value='" + valarry[i] + "'/>");
                    $target.appendTo($box);
                }
                $input.after($box);
            }
        },
        jbringBackSuggest: function (args) {
            //检查是否暂存有表格
            if (itemlookup.$table) {
                $.jItemDetails.initParma(itemlookup.$table);
                var _args = args.split("|");
                $.each(_args, function (k, arg) {
                    var obj = DWZ.jsonEval(arg);
                    $.each(obj, function (name, value) {
                        $.each($.jItemDetails.fields, function (i, o) {
                            if (o && o.name && o.name.length > 0 && o.name.indexOf("." + name) >= 0) {
                                {
                                    $.jItemDetails.fields[i].defaultVal = value;
                                }
                            }
                        });
                    });
                    $.jItemDetails.addRow(1);
                });
                $.pdialog.closeCurrent();
                $.jItemDetails.initSuffix(itemlookup.$table.find("tbody"));
                var onAfter = itemlookup.$table.attr("onAfter");
                if (onAfter) onAfter(args);
                $("[layoutH]").layoutH();
            }
        },
        jbringBack: function (args) {
            $.jbringBackSuggest(args);
        }
    });
    $.fn.extend({
        jmultLookup: function () {
            return this.each(function () {
                var $this = $(this);//, args = "";
                $this.click(function (event) {
                    var $unitBox = $this.parents(".unitBox:first");
                    var args = "";
                    $unitBox.find("[name='" + $this.attr("jmultLookup") + "']").filter(":checked").each(function () {
                        var val = $(this).val();                       
                        if (val && val.length > 0)
                            args += val + "|";
                        //for (var key in _args) {
                        //    var value = args[key] ? args[key] + "," : "";
                        //    args[key] = value + _args[key];
                        //}
                    });
                    args = args.substring(0, args.length - 1);
                    if ($.isEmptyObject(args)) {
                        alertMsg.error($this.attr("warn") || DWZ.msg("alertSelectMsg"));
                        return false;
                    }
                    $.jbringBack(args);
                });
            });
        },
    });
    $.jItemDetails = {
        $table: null,
        $tbody: null,
        _op: {},
        fields: [],
        initParma: function ($thistab) {
            $table = $thistab.css("clear", "both");
            $tbody = $table.find("tbody");
            _op = {
                id: $table.attr('id') || "tableEditor",
                isEdit: !$table.attr("isedit") || $table.attr("isedit") == "true",
                addButTxt: $table.attr('addButton') || "Add New",
                lookupgroup: $table.attr("lookupgroup") || "",
                href: $table.attr("href") || "#"
            };
            $.jItemDetails.fields = [];
            $table.find("tr:first th[type]").each(function (i) {
                var $th = $(this);
                var field = {
                    type: $th.attr("type") || "text",
                    patternDate: $th.attr("dateFmt") || "yyyy-MM-dd",
                    name: $th.attr("name") || "",
                    defaultVal: $th.attr("defaultVal") || "",
                    size: $th.attr("size") || "12",
                    enumUrl: $th.attr("enumUrl") || "",
                    lookupGroup: $th.attr("lookupGroup") || "",
                    lookupUrl: $th.attr("lookupUrl") || "",
                    lookupPk: $th.attr("lookupPk") || "id",
                    suggestUrl: $th.attr("suggestUrl"),
                    suggestFields: $th.attr("suggestFields"),
                    postField: $th.attr("postField") || "",
                    fieldClass: $th.attr("fieldClass") || "",
                    fieldAttrs: $th.attr("fieldAttrs") || "",
                    tabindex: $th.attr("tabindex") || "",
                    style: $th.attr("style") || "",
                    targeter: $th.attr("targeter") || "",
                    ajax: $th.attr("ajax") || "",
                    columns: $th.attr("columns") || "",
                    datatext: $th.attr("datatext") || "",
                    datavalue: $th.attr("datavalue") || "",
                    filter: $th.attr("filter") || "",
                    filttype: $th.attr("filttype") || "",
                    onchange: $th.attr("onchange") || "",
                    readonly: $th.attr("readonly") || ""
                };
                $.jItemDetails.fields.push(field);
            });
        },
        init: function ($thistab) {
            $.jItemDetails.initParma($thistab);
            var isEdit = _op.isEdit;
            if (!isEdit) {
                $tbody.find(">tr>td").find(".btnDel").each(function (i) {
                    $(this).remove();
                });
                $tbody.find(">tr>td").find(":input").each(function (i) {
                    $(this).addClass("readonly");
                    $(this).attr("disabled", "true");
                    $(this).removeClass("select3");
                });
            }
            $.jItemDetails.initSuffix($tbody);//格式化下标
           
            $tbody.find("a.btnDel").click(function () {
                var $btnDel = $(this);

                if ($btnDel.is("[href^=javascript:]")) {
                    $btnDel.parents("tr:first").remove();
                    $.jItemDetails.initSuffix($tbody);
                    return false;
                }

                function delDbData() {
                    $.ajax({
                        type: 'POST', dataType: "json", url: $btnDel.attr('href'), cache: false,
                        success: function () {
                            $btnDel.parents("tr:first").remove();
                            $.jItemDetails.initSuffix($tbody);
                        },
                        error: DWZ.ajaxError
                    });
                }

                if ($btnDel.attr("title")) {
                    alertMsg.confirm($btnDel.attr("title"), { okCall: delDbData });
                } else {
                    delDbData();
                }

                return false;
            });
            function getPKs() {
                var pk = $table.attr("pk");
                var pks = "";
                $tbody.find(">tr>td").find(":input").each(function (i) {
                    var name = $(this).attr("name");
                    if (name.indexOf("." + pk) >= 0) {
                        pks += $(this).val() + ",";
                    }
                });
                pks = pks.substring(0, pks.length - 1);
                return pks;
            }
            var addButTxt = _op.addButTxt
            if (addButTxt) {
                var id = _op.id;
                var isRowNum = !$table.attr('isrownum') || $table.attr('isrownum') == "true";
                var isButton = isEdit && (!$table.attr('isbutton') || $table.attr('isbutton') == "true");
                var $div = $("<div id='div" + id + "' style='display:" + (isButton ? "block" : "none") + "'></div>").insertBefore($table);
                var $rowNum = $('<input type="' + (isRowNum ? "text" : "hidden") + '" id="input' + id + '" name="dwz_rowNum" class="textInput"  style="margin:2px;" value="1" size="2"/>').prependTo($div);
                var $addBut = $('<div class="button" style="float:none"><div class="buttonContent"><button type="button" id="btn' + id + '" class="e2t-ignore" lookupgroup="' + _op.lookupgroup + '" href="' + _op.href + '">' + addButTxt + '</button></div></div>').prependTo($div).find("button");

                var trTm = "";
                $addBut.click(function () {
                    if (_op.lookupgroup && _op.lookupgroup.length > 0) {
                        itemlookup.$table = $thistab;
                        var $this = $thistab;
                        var title = $this.attr("title") || addButTxt;
                        var rel = $this.attr("rel") || "_blank";
                        var options = {};
                        var w = $this.attr("width");
                        var h = $this.attr("height");
                        if (w) options.width = w;
                        if (h) options.height = h;
                        options.max = eval($this.attr("max") || "false");
                        options.mask = eval($this.attr("mask") || "false");
                        options.maxable = eval($this.attr("maxable") || "true");
                        options.minable = eval($this.attr("minable") || "true");
                        options.fresh = eval($this.attr("fresh") || "true");
                        options.resizable = eval($this.attr("resizable") || "true");
                        options.drawable = eval($this.attr("drawable") || "true");
                        options.close = eval($this.attr("close") || "");
                        options.param = $this.attr("param") || "";

                        var url = unescape($this.attr("href")).replaceTmById($(event.target).parents(".unitBox:first"));
                        var pks = getPKs();
                        if (pks && pks.length > 0) {
                            var pk = $table.attr("pk");
                            p = pk + "=" + pks;
                            url = url + (url.indexOf("?") > 0 ? "&" : "?") + p;
                        }
                        DWZ.debug(url);
                        if (!url.isFinishedTm()) {
                            alertMsg.error($this.attr("warn") || DWZ.msg("alertSelectMsg"));
                            return false;
                        }
                        $.pdialog.open(url, rel, title, options);
                        event.preventDefault();
                        return false;
                    }
                    else {
                        $.jItemDetails.addRow($rowNum.val());
                        $.jItemDetails.initSuffix($tbody);
                        $("[layoutH]").layoutH();
                    }
                });
            }
        },
        addRow: function ($rowNum) {
            var trTm = "";
            if (!trTm) trTm = $.jItemDetails.trHtml($.jItemDetails.fields);
            var rowNum = 1;
            try { rowNum = parseInt($rowNum) } catch (e) { }

            for (var i = 0; i < rowNum; i++) {
                var $tr = $(trTm);
                $tr.appendTo($tbody).initUI().find("a.btnDel").click(function () {
                    $(this).parents("tr:first").remove();
                    $.jItemDetails.initSuffix($tbody);
                    return false;
                });
            }
            //$.jItemDetails.initSuffix($tbody);
            //$("[layoutH]").layoutH();
        },
        _bindData: function (obj) {
            var $ref = $(obj)
            $.ajax({
                dataType: "json", type: "GET", url: $ref.attr("ajax"), cache: false, async: false,
                data: {},
                success: function (json) {
                    if (!json) return;
                    var html = '';
                    var jsonarr = json;//eval("(" + json + ")");
                    var datavalue = $ref.attr("datavalue") || "";
                    var datatext = $ref.attr("datatext") || "";
                    datavalue = datavalue.substr(0, datavalue.indexOf(":"));
                    datatext = datatext.substr(0, datatext.indexOf(":"));
                    $ref.find(">option").remove();
                    $.each(jsonarr, function (i) {
                        var index = 0;
                        var val = "";
                        var text = "";
                        var other = "";
                        for (var key in jsonarr[i]) {
                            if (datavalue.length > 0) {
                                if (key == datavalue) val = jsonarr[i][key];
                            }
                            else {
                                if (index == 0) val = jsonarr[i][key];
                            }
                            if (datatext.length > 0) {
                                if (key == datatext) text = jsonarr[i][key];
                            }
                            else {
                                if (index == 1) text = jsonarr[i][key];
                            }
                            if (datavalue.length > 0 && datatext.length > 0) {
                                if (key != datavalue && key != datatext) {
                                    other += "" + key + ":'" + jsonarr[i][key] + "',";
                                }
                            }
                            else {
                                if (index > 1) other += "'" + key + "':'" + jsonarr[i][key] + "',";
                            }
                            index++;
                        }
                        if (other && other.length > 0) other = other.substr(0, other.length - 1)
                        html = '<option value="' + val + '" ' + datavalue + '="' + val + '" ' + datatext + '="' + text + '" other="[{' + other + '}]">' + text + '</option>';
                        $(html).prependTo($ref);
                    });

                },
                error: DWZ.ajaxError
            });

        },

        /**
         * 删除时重新初始化下标
         */
        initSuffix: function ($tbody) {
            $tbody.find('>tr').each(function (i) {
                $(':input,span.index, a.btnLook, a.btnAttach', this).each(function () {
                    var $this = $(this), name = $this.attr('name'), val = $this.val();
                    var fieldattrs = $this.attr("fieldattrs");
                    if (name) $this.attr('name', name.replaceSuffix2(i));
                    if (fieldattrs) $this.attr('fieldattrs', fieldattrs.replaceSuffix2(i));
                    var val = $this.attr('value');
                    if (val) $this.attr('value', val.replaceSuffix(i));
                    if (!$this.is("select")) {
                        if ($this.text()) $this.text($this.text().replaceSuffix(i + 1));
                    }
                    //格式化tabindex
                    var tab = $this.attr("tab");
                    if (tab) {
                        var s = parseInt(tab) + i * 100;
                        $this.attr('tabindex', s);
                    }
                    var lookupGroup = $this.attr('lookupGroup');
                    if (lookupGroup) { $this.attr('lookupGroup', lookupGroup.replaceSuffix(i)); }

                    var suffix = $this.attr("suffix");
                    if (suffix) { $this.attr('suffix', suffix.replaceSuffix(i)); }

                    if (val && val.indexOf("#index#") >= 0) $this.val(val.replace('#index#', i + 1));
                });
            });
        },

        tdHtml: function (field) {
            var html = '', suffix = '';

            if (field.name.endsWith("[#index#]")) suffix = "[#index#]";
            else if (field.name.endsWith("[]")) suffix = "[]";

            var suffixFrag = suffix ? ' suffix="' + suffix + '" ' : '';

            var attrFrag = '';
            if (field.fieldAttrs) {
                var attrs = DWZ.jsonEval(field.fieldAttrs);
                for (var key in attrs) {
                    attrFrag += key + '="' + attrs[key] + '"';
                }
            }
            switch (field.type) {
                case 'del':
                    html = '<a href="javascript:void(0)" class="btnDel ' + field.fieldClass + '">删除</a>';
                    break;
                case 'lookup':
                    var suggestFrag = '';
                    if (field.suggestFields) {
                        suggestFrag = 'autocomplete="off" lookupGroup="' + field.lookupGroup + '"' + suffixFrag + ' suggestUrl="' + field.suggestUrl + '" suggestFields="' + field.suggestFields + '"' + ' postField="' + field.postField + '"';
                    }

                    html = '<input type="hidden" name="' + field.lookupGroup + '.' + field.lookupPk + suffix + '" tabindex="' + field.tabindex + '"/>'
                        + '<input type="text" name="' + field.name + '"' + suggestFrag + ' lookupPk="' + field.lookupPk + '" size="' + field.size + '" class="' + field.fieldClass + '"  tab="' + field.tabindex + '"/>'
                        + '<a class="btnLook" href="' + field.lookupUrl + '" lookupGroup="' + field.lookupGroup + '" ' + suggestFrag + ' lookupPk="' + field.lookupPk + '"  tab="' + field.tabindex + '" title="查找带回">查找带回</a>';
                    break;
                case 'attach':
                    html = '<input type="hidden" name="' + field.lookupGroup + '.' + field.lookupPk + suffix + '"  tab="' + field.tabindex + '"/>'
                        + '<input type="text" name="' + field.name + '" size="' + field.size + '" readonly="readonly" class="' + field.fieldClass + '"  tab="' + field.tabindex + '"/>'
                        + '<a class="btnAttach" href="' + field.lookupUrl + '" lookupGroup="' + field.lookupGroup + '" ' + suffixFrag + ' lookupPk="' + field.lookupPk + '" width="560" height="300"  tab="' + field.tabindex + '" title="查找带回">查找带回</a>';
                    break;
                case 'enum':
                    $.ajax({
                        type: "POST", dataType: "html", async: false,
                        url: field.enumUrl,
                        data: { inputName: field.name },
                        success: function (response) {
                            html = response;
                        }
                    });
                    break;
                case 'date':
                    html = '<input type="text" name="' + field.name + '" value="' + field.defaultVal + '" class="date ' + field.fieldClass + '" dateFmt="' + field.patternDate + '" size="' + field.size + '"  tab="' + field.tabindex + '" ' + field.readonly + '/>'
                        + '<a class="inputDateButton" href="javascript:void(0)">选择</a>';
                    break;
                case 'select3':
                    html = '<select class="select3" name="' + field.name + '" targeter="' + field.targeter + '" style="' + field.style + '" ajax="' + field.ajax + '" columns="' + field.columns + '" datatext="' + field.datatext + '" datavalue="' + field.datavalue + '" filter="' + field.filter + '" filttype="' + field.filttype + '" onchange="' + field.onchange + '" tab="' + field.tabindex + '" ' + field.readonly + '>';
                    if (field.targeter && field.targeter.length > 0) {
                        html += $("#" + field.targeter).html();
                    }
                    html += "</select>";
                    break;
                case 'select':
                    html = '<select name="' + field.name + '" style="' + field.style + '" onchange="' + field.onchange + '" tab="' + field.tabindex + '" ' + field.readonly + '>';
                    if (field.targeter && field.targeter.length > 0) {
                        html += $("#" + field.targeter).html();
                    }
                    html += "</select>";
                    break;
                case 'label':
                    html = '<span class="index" name="' + field.name + '" value="' + field.defaultVal + '">' + field.defaultVal + '</span>';
                    break;
                default:
                    html = '<input type="' + field.type + '" name="' + field.name + '" value="' + field.defaultVal + '" size="' + field.size + '" targeter="' + field.targeter + '" ajax="' + field.ajax + '" class="' + field.fieldClass + '" ' + attrFrag + '  tab="' + field.tabindex + '"  ' + field.readonly + '/>';
                    break;
            }
            return '<td>' + html + '</td>';
        },

        trHtml: function (fields) {
            var html = '';
            $(fields).each(function () {
                html += $.jItemDetails.tdHtml(this);
            });
            return '<tr class="unitBox">' + html + '</tr>';
        }
    };
})(jQuery);